<template>
  <div class="update-photo">
    <img class="image" :src="image" ref="image" />
    <van-nav-bar
      left-text="取消"
      right-text="确认"
      @click-left="onCancel"
      @click-right="onConfirm"
    />
  </div>
</template>

<script>
import { updateUserPhoto } from "@/api/user";
import "cropperjs/dist/cropper.css";
import Cropper from "cropperjs";

export default {
  name: "UpdatePhoto",
  props: ["file"],
  data() {
    return {
      image: window.URL.createObjectURL(this.file),
      cropper: null, // 裁切器实例
    };
  },
  methods: {
    // promise包装
    getCroppedCanvas() {
      return new Promise((resolve) => {
        this.cropper.getCroppedCanvas().toBlob((file) => {
          resolve(file);
        });
      });
    },
    // 点击确认
    async onConfirm() {
      this.$toast({
        message: "保存中",
        forbidclick: true,
      });

      const file = await this.getCroppedCanvas();

      const fd = new FormData();
      fd.append("photo", file);

      await updateUserPhoto(fd);

      this.$toast.success("保存成功");
      this.$emit("update-success", window.URL.createObjectURL(file));
      this.onCancel();
    },
    // 点击取消
    onCancel() {
      window.URL.revokeObjectURL(this.image);
      this.$emit("close");
    },
  },
  mounted() {
    const image = this.$refs.image;
    this.cropper = new Cropper(image, {
      viewMode: 1,
      dragMode: "move",
      aspectRatio: 1,
      cropBoxMovable: false,
      cropBoxResizable: false,
      background: false,
      movable: true,
    });
  },
};
</script>

<style scoped lang="less">
.update-photo {
  height: 100%;
  display: flex;
  align-items: center;

  .image {
    width: 100%;
  }

  .van-nav-bar {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: unset;
  }
}
</style>
